package com.example.micro.thread.demo;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;

/**
 * @program: thread
 * @description: ForkJoinPool测试类
 * @author: jym
 * @create: 2020/01/28
 */
public class ForkJoinPoolTest {

    public static void main(String[] args) {
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        long start = System.currentTimeMillis();
        JymForkJoinDemo jymForkJoinDemo = new JymForkJoinDemo(0L, 10000000000L);
        forkJoinPool.invoke(jymForkJoinDemo);
        long end = System.currentTimeMillis();
        System.out.println(end - start);
        long sum = 0L;
        for (long i = 0L; i < 10000000000L; i++) {
            sum += i;
        }
        long end1 = System.currentTimeMillis();
        System.out.println(end1 - end);
    }

}

class JymForkJoinDemo extends RecursiveTask<Long> {

    private final Long start;
    private final Long end;

    public JymForkJoinDemo(Long start, Long end) {
        this.start = start;
        this.end = end;
    }

    public static final Long BORDER = 50000000L;

    @Override
    protected Long compute() {
        long length = end - start;
        if (length <= BORDER) {
            long sum = 0L;
            for (long i = start; i < end; i++) {
                sum += i;
            }
            return sum;
        } else {
            long middle = (start + end) / 2;
            JymForkJoinDemo left = new JymForkJoinDemo(start, middle);
            left.fork();
            JymForkJoinDemo right = new JymForkJoinDemo(middle, end);
            right.fork();
            return left.join() + right.join();
        }
    }

}
